#include <stdlib.h>
#include <wiiuse/wpad.h>
#include <fat.h>
#include "map.h"

#include "tile_map.h"

#include "tile_png.h"
#include "sky_png.h"

extern void Debug(const char *msg);

using namespace std;


const int TileMap1Width = 16;
const int TileMap1Height = 16;
const int Map1Width = 512;
const int Map1Height = 30;


Map::Map() {
	texMarioWorld = GRRLIB_LoadTexture(tile_png);
	GRRLIB_InitTileSet(texMarioWorld, TileMap1Width, TileMap1Height, 0);
	
	texSky = GRRLIB_LoadTexture(sky_png);
	
	for(int i = 0; i < COINS; i++)
		myCoin[i] = new Coin(-16, -16);
	
	cptx = 0;
	cnt = 0;
	
	/*for(int i = 0; i < Map1Width; i++) {
		for(int j = 0; j < Map1Height; j++) {
			if((GetMapInfo(j, i) == 1028) && cnt <= COINS) {
				myCoin[cnt]->SetXY((i-1)*TileMap1Width + TileMap1Width/2, (j-1)*TileMap1Width - TileMap1Width/2);
				cnt++;
			}
		}
	}*/
	
	cnt = 0;
}

Map::~Map() {
	GRRLIB_FreeTexture(texMarioWorld);
	GRRLIB_FreeTexture(texSky);
	
	for(int i = 0; i < COINS; i++) {
		if(myCoin[i]) {
			delete myCoin[i];
		}
	}
}

void Map::Draw(Player &pl) {
	int x = fix_norm(pl.GetScroll());
	
	cptx = x % TileMap1Width;
	
	// Draw blue sky in bg
	GRRLIB_DrawImg (0, 0, texSky, 0, 1, 1, GRRLIB_WHITE);
	
	for(int i = 0; i < COINS; i++) {
		if(myCoin[i] && myCoin[i]->Collision(pl.GetX(), pl.GetY(), 28)) {
			delete myCoin[i];
			myCoin[i] = 0;
			cnt++;
		}
	}
	
	// Draw front background
	for(int _y = 1; _y < Map1Height+1; _y++) {
		for(int _x = 0; _x < 42; _x++) {
			if(GetMapData(_y-1, _x+(x/TileMap1Width)) != 0) {
				GRRLIB_DrawTile((_x*TileMap1Width-cptx-TileMap1Width), _y*TileMap1Height-TileMap1Height, texMarioWorld, 0, 1, 1, GRRLIB_WHITE, GetMapData(_y-1, _x+(x/TileMap1Width))-1);
			}
		}
	}
	for(int i = 0; i < COINS; i++) {
		if(myCoin[i])
			myCoin[i]->Render(pl.GetScroll());
	}
}

size_t Map::GetLength() {
	return TileMap1Width * Map1Width;
}

size_t Map::GetCoins() {
	return cnt;
}
